package grupobbva.pe.operhc.action;


import static grupobbva.pe.operhc.util.Constant.TIPO_ARCHIVO_DISCLAMER;
import static grupobbva.pe.operhc.util.Constant.NAME_APP_LOG;
import grupobbva.pe.operhc.service.ParametroService;
import grupobbva.pe.operhc.service.ParametroServiceImpl;
import grupobbva.pe.operhc.util.Utilities;


import java.io.File;
import java.io.FileInputStream;

import java.util.Date;

import java.util.Map;

import javax.activation.MimetypesFileTypeMap;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class DownloadFileAction extends Action{
	private ParametroService parametroService = null;
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {		
		
		
              
        try 
    	{
        	String  YYYYMMDD_HHMMSS_ = "yyyyMMdd_hhmmss";
        	parametroService = new ParametroServiceImpl(); 
        	Map<String, String> parametroBroker = parametroService.getMapParametersByParameterType(TIPO_ARCHIVO_DISCLAMER);
			String ruta = parametroBroker.get("RUTA_LOG");
        	File archivo = new File(ruta);
        	//return an application file instead of html page
        	if(archivo.exists()){
				String archivoFileName = NAME_APP_LOG+"_"+Utilities.formatFecha(new Date(),YYYYMMDD_HHMMSS_)+".log";
	        	 response.setContentType(new MimetypesFileTypeMap().getContentType(archivo));
	             response.setHeader("Content-Disposition","attachment;filename=\"" + archivoFileName + "\""); 
	        	
	        	//Get it from file system
	        	FileInputStream in = new FileInputStream(archivo);
	        	ServletOutputStream out = response.getOutputStream();
	        	 
	        	byte[] outputByte = new byte[4096];
	        	//copy binary contect to output stream
	        	while(in.read(outputByte, 0, 4096) != -1)
	        	{
	        		out.write(outputByte, 0, 4096);
	        	}
	        	in.close();
	        	out.flush();
	        	out.close();
        	}else{
        		
        	}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
		return null;
	}

}